package com.dhp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dhp.common.BaseResponse;
import com.dhp.common.ErrorCode;
import com.dhp.exception.BusinessException;
import com.dhp.mapper.InterfaceInfoMapper;
import com.dhp.model.dto.userInterfaceInfo.UserInterfaceInfoApplyInvokeCountRequest;
import com.dhp.model.dto.userInterfaceInfo.listMyInterfaceRequest;
import com.dhp.model.entity.InterfaceInfo;
import com.dhp.model.entity.User;
import com.dhp.model.entity.UserInterfaceInfo;
import com.dhp.model.vo.UserInterfaceVO;
import com.dhp.service.UserInterfaceInfoService;
import com.dhp.mapper.UserInterfaceInfoMapper;
import com.dhp.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
* @author Dhp
* @description 针对表【user_interface_info(用户调用接口关系)】的数据库操作Service实现
* @createDate 2024-07-26 16:30:18
*/
@Service
public class UserInterfaceInfoServiceImpl extends ServiceImpl<UserInterfaceInfoMapper, UserInterfaceInfo>
    implements UserInterfaceInfoService{

    @Autowired
    private UserService userService;

    @Resource
    private InterfaceInfoMapper interfaceInfoMapper;
    /**
     * 申请接口调用次数
     * @param applyRequest
     * @param request
     * @return
     */
    @Override
    public Boolean applyInvokeCount(UserInterfaceInfoApplyInvokeCountRequest applyRequest, HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        if (null == loginUser){
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR , "用户未登录");
        }

        // 查询是否存在记录
        LambdaQueryWrapper<UserInterfaceInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserInterfaceInfo::getUserid , loginUser.getId()).eq(UserInterfaceInfo::getInterfaceinfoId , applyRequest.getInterfaceId());
        UserInterfaceInfo record = getOne(queryWrapper);
        //不存在则插入
        if (null == record){
            record = new UserInterfaceInfo();
            record.setUserid(loginUser.getId());
            record.setInterfaceinfoId(applyRequest.getInterfaceId());
            record.setTotalNum(0);
            record.setLeftNum(applyRequest.getCount());
            return save(record);
        }else{
            //存在则更新总数和剩余数量
            record.setLeftNum(record.getLeftNum() + applyRequest.getCount());
            return updateById(record);
        }
    }

    /**
     * 获取登录用户的接口
     * @param request
     * @return
     */
    @Override
    public Page<UserInterfaceVO> listMyInterface(listMyInterfaceRequest myInterfaceRequest , HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        if (null == loginUser){
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }

        //获取相关记录
        LambdaQueryWrapper<UserInterfaceInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserInterfaceInfo::getUserid , loginUser.getId());
        Page<UserInterfaceInfo> page = this.page(new Page<>(myInterfaceRequest.getCurrent(), myInterfaceRequest.getPageSize()), queryWrapper);
        List<UserInterfaceInfo> userInterfaceInfoList = page.getRecords();
        if (CollectionUtil.isEmpty(userInterfaceInfoList)){
            return new Page<>();
        }

        //查询关联的接口信息
        List<Long> interfaceIds = userInterfaceInfoList.stream().map(item -> item.getInterfaceinfoId()).collect(Collectors.toList());
        List<InterfaceInfo> interfaceInfos = interfaceInfoMapper.selectBatchIds(interfaceIds);
        //构造interfaceId -> interface的map
        Map<Long, List<InterfaceInfo>> idToInfoMap = interfaceInfos.stream().collect(Collectors.groupingBy(InterfaceInfo::getId));

        //构造返回list
        List<UserInterfaceVO> userInterfaceVOList = new ArrayList<>();
        for (UserInterfaceInfo userInterfaceInfo : userInterfaceInfoList) {
            UserInterfaceVO item = new UserInterfaceVO();
            BeanUtils.copyProperties(userInterfaceInfo , item);
            item.setInterfaceInfo(idToInfoMap.get(userInterfaceInfo.getInterfaceinfoId()).get(0));
            userInterfaceVOList.add(item);
        }

        if (StringUtils.isNotEmpty(myInterfaceRequest.getName())){
            userInterfaceVOList = userInterfaceVOList.stream().filter(item -> item.getInterfaceInfo().getName().contains(myInterfaceRequest.getName()))
                    .collect(Collectors.toList());
        }

        Page<UserInterfaceVO> resPage = new Page<>(page.getCurrent() , page.getSize());
        resPage.setTotal(page.getTotal());
        resPage.setRecords(userInterfaceVOList);

        return resPage;
    }
}




